/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package com.ruoyi.web.controller.delivery;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jianqiao.delivery.address.domain.YxSystemCity;
import com.jianqiao.delivery.address.domain.YxUserAddress;
import com.jianqiao.delivery.address.domain.param.AddressParam;
import com.jianqiao.delivery.address.domain.param.IdParam;
import com.jianqiao.delivery.address.domain.vo.CityLanguageChangeVo;
import com.jianqiao.delivery.address.domain.vo.CityVo;
import com.jianqiao.delivery.address.domain.vo.YxUserAddressQueryVo;
import com.jianqiao.delivery.address.mapper.YxSystemCityMapper;
import com.jianqiao.delivery.address.service.YxSystemCityService;
import com.jianqiao.delivery.address.service.YxUserAddressService;
import com.jianqiao.delivery.delivery.service.ResolveAddressService;
import com.jianqiao.delivery.util.CityTreeUtil;
import com.ruoyi.common.constant.ShopConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 用户地前端控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-28
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户地址", tags = "用户:用户地址")
public class UserAddressController {

    private final YxUserAddressService userAddressService;
    private final YxSystemCityService systemCityService;

    @Autowired
    private ResolveAddressService resolveAddressService;

//    @Cacheable(cacheNames = ShopConstants.ECOMMERCE_REDIS_CITY_KEY)
    @GetMapping("/city_list")
    @ApiOperation(value = "城市列表",notes = "城市列表")
    public AjaxResult getTest(HttpServletRequest request) {
        String countryflag = request.getHeader("Countryflag");
        System.out.println("city_list");
        LambdaQueryWrapper<YxSystemCity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxSystemCity::getLanguageType ,countryflag);
        List<YxSystemCity> yxSystemCities = systemCityService.list(queryWrapper);

        List<CityVo> cityVOS = Lists.newArrayList();

        for (YxSystemCity systemCity : yxSystemCities){
            CityVo cityVO = new CityVo();

            cityVO.setV(systemCity.getCityId());
            cityVO.setN(systemCity.getName());
            cityVO.setPid(systemCity.getParentId());

            cityVOS.add(cityVO);
        }

        return AjaxResult.success(CityTreeUtil.list2TreeConverter(cityVOS, 0));
    }

    /**
    * 添加或修改地址
    */
//    @AppLog(value = "添加或修改地址", type = 1)
    @PostMapping("/address/edit")
    @ApiOperation(value = "添加或修改地址",notes = "添加或修改地址")
    public AjaxResult addYxUserAddress(@Valid @RequestBody AddressParam param){
        Long uid = SecurityUtils.getUserId();
        Long id = userAddressService.addAndEdit(uid,param);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("id",id);
        return AjaxResult.success(map);
    }

    /**
     * 设置默认地址
     */
//    @AppLog(value = "设置默认地址", type = 1)
    @PostMapping("/address/default/set")
    @ApiOperation(value = "设置默认地址",notes = "设置默认地址")
    public AjaxResult setDefault(@Valid @RequestBody IdParam idParam){
        Long uid = SecurityUtils.getUserId();
        userAddressService.setDefault(uid,Long.valueOf(idParam.getId()));
        return AjaxResult.success();
    }

    /**
    * 删除用户地址
    */
    @PostMapping("/address/del")
    @ApiOperation(value = "删除用户地址",notes = "删除用户地址")
    public AjaxResult deleteYxUserAddress(@RequestBody IdParam idParam){
        String id = idParam.getId();
//        userAddressService.removeById(id);
        userAddressService.delAddress(id);
        return AjaxResult.success();
    }

    /**
     * 用户地址列表
     */
    @GetMapping("/address/list")
    @ApiOperation(value = "用户地址列表",notes = "用户地址列表")
    public AjaxResult getYxUserAddressPageList(@RequestParam(value = "page",defaultValue = "1") int page,
                                                                          @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = SecurityUtils.getUserId();
        List<YxUserAddressQueryVo> addressQueryVos = userAddressService.getList(uid,page,limit);
        return AjaxResult.success(addressQueryVos);
    }

    /**
     * 地址详情
     */
    @GetMapping("/address/detail/{id}")
    @ApiOperation(value = "地址详情",notes = "地址详情")
    public AjaxResult addressDetail(@PathVariable String id){
        if(StrUtil.isBlank(id) || !NumberUtil.isNumber(id)){
            throw new RuntimeException("参数非法");
        }
        return AjaxResult.success(userAddressService.getDetail(Long.valueOf(id)));
    }

    /**
      *methood: 获取默认地址
      *auth: cyx
      *time: 2024/7/31 10:47
    **/
    @GetMapping("/address/default")
    public AjaxResult getDefault(){
        Long userId = SecurityUtils.getUserId();
        YxUserAddress defaultAddress = userAddressService.getDefault(userId);
        return AjaxResult.success(defaultAddress);
    }

    @GetMapping("/getAll")
    public void getAll(){
        List<YxSystemCity> list = systemCityService.list();
        ArrayList<CityLanguageChangeVo> newCityList = new ArrayList<>();
        for (YxSystemCity yxSystemCity : list){
            String name = yxSystemCity.getName();
            String mergerName = yxSystemCity.getMergerName();
            CityLanguageChangeVo cityLanguageChangeVo = new CityLanguageChangeVo();
            cityLanguageChangeVo.setName(name);
            cityLanguageChangeVo.setMergerName(mergerName);
            newCityList.add(cityLanguageChangeVo);
        }
        for (CityLanguageChangeVo cityLanguageChangeVo : newCityList){
            String name = cityLanguageChangeVo.getName();
            String mergerName = cityLanguageChangeVo.getMergerName();
            String newStr = name + ":" + mergerName;
            System.out.println(newStr);
        }
//        //读取翻译后的txt文件
        String txtPath = "C:\\Users\\os\\Desktop\\cityList.txt";
        ArrayList<YxSystemCity> updateCityList = new ArrayList<>();
        ArrayList<CityLanguageChangeVo> idnCityList = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(txtPath));
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理每一行
                System.out.println(line);
                String[] split = line.split(":");
                CityLanguageChangeVo cityLanguageChangeVo = new CityLanguageChangeVo();
                cityLanguageChangeVo.setName(split[0]);
                cityLanguageChangeVo.setMergerName(split[1]);
                idnCityList.add(cityLanguageChangeVo);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        for (int i = 0 ;i < idnCityList.size() ;i ++){
            CityLanguageChangeVo cityLanguageChangeVo = idnCityList.get(i);
            String newName = cityLanguageChangeVo.getName();
            String newMergerName = cityLanguageChangeVo.getMergerName();

            YxSystemCity yxSystemCity = list.get(i);
            yxSystemCity.setName(newName);
            yxSystemCity.setMergerName(newMergerName);

            updateCityList.add(yxSystemCity);
        }
        for (YxSystemCity yxSystemCity : updateCityList){
            System.out.println(yxSystemCity);
        }
        int change = systemCityService.change(list);
//        int updated = yxSystemCityMapper.updateCityLanguage(updateCityList);
        System.out.println(change);
//        System.out.println(newCityList);
    }

    @PostMapping("/address/resolve")
    public AjaxResult resolve(@RequestBody Map<String ,String> paramMap ,HttpServletRequest request) throws IOException {
        String countryFlag = request.getHeader("Countryflag");
        String info = paramMap.get("info");
        AjaxResult resultMap = AjaxResult.error();
//        if ("ja".equals(countryFlag)) {
        resultMap = resolveAddressService.resolveJpAddressService(info);
        if (resultMap.isError()) {
            resultMap = resolveAddressService.resolveIndAddressService(info);
        }
//        } else if ("in".equals(countryFlag)) {
//            resultMap = resolveAddressService.resolveIndAddressService(info);
//        }

        return resultMap;
    }

//    @GetMapping("/address/getAddress")
//    public void get() throws IOException {
//        indAddressService.getAddress();
//    }
}

